package com.decent.manager.system.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.decent.common.enums.ErrorCodeEnum;
import com.decent.common.exception.ErrorCodeException;
import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author 张子旭
 * @date 2022/1/20
 */
public class CommonServletUtil {
    /**
     * 获取 HttpServletRequest
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNull(servletRequestAttributes)) {
            throw new ErrorCodeException(ErrorCodeEnum.INVALID_PARAMS);
        }
        return servletRequestAttributes.getRequest();
    }

    /**
     * 通过response返回json数据
     *
     * @param response HttpServletResponse
     * @param object   写入数据
     */
    @SneakyThrows
    public static void writeJsonToResponse(HttpServletResponse response, Object object) {
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSONUtil.toJsonStr(object));
        }
    }
}
